package com.qujia.station.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.exception.CustomException;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.MemberManagement;
import com.qujia.station.domain.dto.MemberManagementDto;
import com.qujia.station.domain.dto.MemberManagementQueryDto;
import com.qujia.station.domain.vo.MemberManagementVo;
import com.qujia.station.mapper.MemberManagementMapper;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.MemberManagementService;
import com.qujia.station.service.TeamManagementService;
import com.qujia.station.utils.PermissionsUtil;
import com.qujia.system.domain.SysEnterpriseUser;
import com.qujia.system.service.ISysEnterpriseUserService;
import com.qujia.system.service.ISysUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author PC
 * @description 针对表【member_management(成员管理表)】的数据库操作Service实现
 * @createDate 2023-08-29 16:35:09
 */
@Service
@Slf4j
public class MemberManagementServiceImpl extends ServiceImpl<MemberManagementMapper, MemberManagement>
        implements MemberManagementService {

    @Autowired
    private MemberManagementMapper managementMapper;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysEnterpriseUserService sysEnterpriseUserService;

    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private IEnterpriseService enterpriseService;


    @Override
    public Integer addMember(MemberManagementDto memberManagementDto) {

        String collect = String.join(",", memberManagementDto.getEnterpriseIds());
        log.info("获取用户信息：用户id{}", memberManagementDto.getSalesmanId());
        SysUser sysUser = iSysUserService.selectUserById(memberManagementDto.getSalesmanId());

        if (ObjectUtils.isEmpty(sysUser) || !sysUser.getUserLevel().equals("6")) {
            throw new CustomException("没有找到当前用户或者用户等级不为6");
        }
        MemberManagement management = managementMapper.selectBySalesmanId(sysUser.getUserId());

        if (ObjectUtils.isNotEmpty(management)) {
            throw new CustomException("已经创建过成员");
        }

        MemberManagement memberManagement = MemberManagement.builder()
                .enterpriseId(collect)
                .salesmanId(memberManagementDto.getSalesmanId())
                .salesman(sysUser.getNickName())
                .build();
        log.info("新增成员信息：{}", memberManagement);
        return managementMapper.insert(memberManagement);
    }

    @Override
    @Transactional
    public Integer deleteMemberManagement(String ids) {
        List<String> memberIds = Arrays.asList(ids.split(","));
        for (String memberId : memberIds) {
            MemberManagement memberManagement = managementMapper.selectById(Long.valueOf(memberId));
            Long salesmanId = memberManagement.getSalesmanId();
            Long teamId = memberManagement.getTeamId();

            LambdaUpdateWrapper<MemberManagement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            //条件 设置值
            lambdaUpdateWrapper.eq(MemberManagement::getId, Long.valueOf(memberId))
                    .set(MemberManagement::getStatus, 1)
                    .set(MemberManagement::getUpdateTime, new Date())
                    .set(MemberManagement::getTeamId, null);

            //更新
            this.update(lambdaUpdateWrapper);

            log.info("删除成员信息：{}", salesmanId);
            if (teamId != null){
                //删除团队里该成员id
                teamManagementService.updateTeamMemberId(teamId, salesmanId);
            }
        }
        return 1;
    }

    @Override
    @SneakyThrows
    public Integer updateMemberManagement(MemberManagementDto memberManagementDto) {
        log.info("获取成员信息：id:{}", memberManagementDto.getSalesmanId());
        SysUser sysUser = iSysUserService.selectUserById(memberManagementDto.getSalesmanId());

        MemberManagement managementVo = managementMapper.selectBySalesmanId(memberManagementDto.getSalesmanId());

        if(ObjectUtils.isNotEmpty(managementVo) && !managementVo.getId().equals(memberManagementDto.getId()) && managementVo.getSalesmanId().equals(memberManagementDto.getSalesmanId())){
            throw new CustomException("该用户已经设置为成员了");
        }

        if (ObjectUtils.isEmpty(sysUser) || !"6".equals(sysUser.getUserLevel()) || "1".equals(sysUser.getStatus()) || "2".equals(sysUser.getDelFlag())) {
            throw new CustomException("获取不到当前成员信息或者等级不正确");
        }
        MemberManagement memberManagement1 = managementMapper.selectById(memberManagementDto.getId());
        if (!memberManagement1.getSalesmanId().equals(memberManagementDto.getSalesmanId())){
            teamManagementService.updateTeamMemberId(memberManagement1.getTeamId(), memberManagement1.getSalesmanId());
            MemberManagement memberManagement = MemberManagement.builder().salesmanId(memberManagement1.getSalesmanId()).teamId(null).build();
            managementMapper.updateBySalesmanId(memberManagement);
        }
        String collect = String.join(",", memberManagementDto.getEnterpriseIds());
        MemberManagement memberManagement = MemberManagement.builder().id(memberManagementDto.getId()).salesman(sysUser.getNickName()).salesmanId(memberManagementDto.getSalesmanId()).enterpriseId(collect).updateTime(new Date()).build();
        log.info("修改成员信息：{}", memberManagement);
        return managementMapper.updateById(memberManagement);
    }

    @Override
    public List<MemberManagementVo> selectMemberManagement(MemberManagementQueryDto memberManagementDto) {
        List<MemberManagementVo> memberManagements = managementMapper.selectMemberList(memberManagementDto);
        for (MemberManagementVo memberManagement : memberManagements) {
            ArrayList<SysEnterpriseUser> enterprises = new ArrayList<>();
            String enterpriseId = memberManagement.getEnterpriseIds();
            log.info("获取油企信息：油企id：{}", enterpriseId);
            for (String id : enterpriseId.split(",")) {
                SysEnterpriseUser sysEnterpriseUser = sysEnterpriseUserService.selectSysEnterpriseUserById(Long.valueOf(id));
                if (ObjectUtils.isEmpty(sysEnterpriseUser)) {
                    continue;
                }
                enterprises.add(sysEnterpriseUser);
            }
            memberManagement.setEnterpriseList(enterprises);
        }
        return memberManagements;
    }

    @Override
    public void updateBySalesmanId(MemberManagement management) {
        managementMapper.updateBySalesmanId(management);
    }

    @Override
    @SneakyThrows
    public List<Long> getMemberEnterpriseId(Long id) {
        ArrayList<Long> enterpriseIds = new ArrayList<>();
        MemberManagement memberManagement = managementMapper.selectBySalesmanId(id);
        if (ObjectUtils.isEmpty(memberManagement)) {
            return enterpriseIds;
        }
        String enterpriseId = memberManagement.getEnterpriseId();


        if (StringUtils.isNotBlank(enterpriseId)){
            for (String s : enterpriseId.split(",")) {
                enterpriseIds.add(Long.valueOf(s));
            }
        }

        return enterpriseIds;
    }

    @Override
    public MemberManagementVo getBySalesmanId(Long id) {
        MemberManagement build = MemberManagement.builder().salesmanId(id).build();
        return managementMapper.selectByMemberId(build);
    }

    @Override
    public void updateMemberManagement(Long leaderId, Long teamId) {
        MemberManagementQueryDto memberManagementQueryDto = new MemberManagementQueryDto();
        memberManagementQueryDto.setLeaderId(leaderId);
        memberManagementQueryDto.setTeamId(teamId);
        List<MemberManagementVo> memberManagementVos = managementMapper.selectMemberList(memberManagementQueryDto);
        for (MemberManagementVo memberManagementVo : memberManagementVos) {
            MemberManagement build = MemberManagement.builder().salesmanId(memberManagementVo.getSalesmanId()).teamId(null).updateTime(new Date()).build();
            managementMapper.updateBySalesmanId(build);
        }
    }

    @Override
    public String getDistrictByEnterpriseId(Long id) {
        MemberManagementQueryDto memberManagementQueryDto = new MemberManagementQueryDto();
        memberManagementQueryDto.setEnterpriseId(id);
        List<MemberManagementVo> memberManagementVos = managementMapper.selectMemberList(memberManagementQueryDto);
        for (MemberManagementVo managementVo : memberManagementVos) {
            return managementVo.getDistrict();
        }
        return null;

    }

    @Override
    public MemberManagement selectBySalesmanId(Long id) {

        return managementMapper.selectBySalesmanId(id);
    }

    @Override
    public List<Long> getEnterpriseIdBySalesmanId(List<Long> salesmanIdList) {
        List<String> enterpriseIdBySalesmanId = managementMapper.getEnterpriseIdBySalesmanId(salesmanIdList);

        ArrayList<Long>  enterpriseIds = new ArrayList<>();
        for (String enterpriseIdss : enterpriseIdBySalesmanId) {
            for (String enterpriseId : enterpriseIdss.split(",")) {
                enterpriseIds.add(Long.valueOf(enterpriseId));
            }
        }

        return  enterpriseIds.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public String getDistrictByEnterpriseIdAndTeamId(Long enterpriseId, List<Integer> districtIds) {
        MemberManagementQueryDto memberManagementQueryDto = new MemberManagementQueryDto();
        memberManagementQueryDto.setEnterpriseId(enterpriseId);
        List<MemberManagementVo> memberManagementVos = managementMapper.getDistrictByEnterpriseIdAndTeamId(memberManagementQueryDto);
        for (MemberManagementVo managementVo : memberManagementVos) {
            if (null != managementVo.getTeamId()){
                return managementVo.getDistrict();
            }
            break;
        }
        return null;
    }
}




